//
//  SLScrollerTextView.m
//  testScroller
//
//  Created by Duke.wu on 16/6/24.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLScrollerTextView.h"

@interface SLScrollerTextView (){
  NSTimer *timer;
}

@property (nonatomic ,strong) NSArray *arrData;


@end


@implementation SLScrollerTextView

- (instancetype)initWithFrame:(CGRect)frame{
  self = [super initWithFrame:frame];
  if (self) {
    [self initView];
  }
  return self;
}

//初始化数据
-(void) initView{
  
  if (!self.arrData) {
    self.arrData = @[@"添加船舶后，请及时更新管理您的船舶相关信息，系统将为您24小时搜索匹配货源信息",@"添加船舶后，请及时更新管理您的船舶相关信息，系统将为您24小时搜索匹配货源信息",@"添加船舶后，请及时更新管理您的船舶相关信息，系统将为您24小时搜索匹配货源信息"];
  }
  
  //文字滚动
  [self initScrollText];
  
  
}

//文字滚动初始化
-(void) initScrollText{
  
  self.showsHorizontalScrollIndicator = NO;   //隐藏水平滚动条
  self.showsVerticalScrollIndicator = NO;     //隐藏垂直滚动条
  [self setBackgroundColor:SLYellowColor];
  
  if (self.arrData) {
    
    CGFloat offsetX = 0 ,i = 0,h = 20;
    
    //设置滚动文字
    UILabel *labText = nil;
    for (NSString *str in self.arrData) {
      labText = [[UILabel alloc] initWithFrame:CGRectMake(
                                                          i * (K_MAIN_VIEW_SCROLLER_LABLE_WIDTH + K_MAIN_VIEW_SCROLLER_LABLE_MARGIN),
                                                          5,
                                                          K_MAIN_VIEW_SCROLLER_LABLE_WIDTH,
                                                          h)];
      [labText setFont:[UIFont systemFontOfSize:15]];
      [labText setTextColor:[UIColor whiteColor]];
      labText.text = str;
      offsetX += labText.frame.origin.x;
      //添加到滚动视图
      [self addSubview:labText];
      i++;
    }
        //设置滚动区域大小
    [self setContentSize:CGSizeMake(offsetX, 0)];
  }
}


//开始滚动
-(void) startScroll{
  
  if (!timer)
    timer = [NSTimer scheduledTimerWithTimeInterval:K_MAIN_VIEW_TEME_INTERVAL target:self selector:@selector(setScrollText) userInfo:nil repeats:YES];
  
  [timer fire];
}


//滚动处理
-(void) setScrollText{
  
  CGFloat startX = self.contentSize.width - K_MAIN_VIEW_SCROLLER_LABLE_WIDTH - K_MAIN_VIEW_SCROLLER_LABLE_MARGIN;
  
  
  CGRect rect;
  CGFloat offsetX = 0.0;
  for (UILabel *lab in self.subviews) {
    rect = lab.frame;
    offsetX = rect.origin.x - K_MAIN_VIEW_SCROLLER_SPACE;
    if (offsetX < -K_MAIN_VIEW_SCROLLER_LABLE_WIDTH){
      offsetX = startX;
      lab.frame = CGRectMake(offsetX, rect.origin.y, rect.size.width, rect.size.height);
    }else{
      [UIView animateWithDuration:K_MAIN_VIEW_TEME_INTERVAL * 2 animations:^{
        lab.frame = CGRectMake(offsetX, rect.origin.y, rect.size.width, rect.size.height);
        
      }];
    }
    
  }
  
  
  
}





/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
